package com.geping.etl.common.controller;

import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.geping.etl.common.entity.*;
import com.geping.etl.common.security.pwd.PwdPolicyService;
import com.geping.etl.common.security.pwd.PwdPolicyServiceDispatcher;
import com.geping.etl.common.service.*;
import com.geping.etl.common.util.BusinessResponse;
import com.geping.etl.common.util.BusinessResult;
import com.geping.etl.common.util.Constants;
import com.geping.etl.common.vo.ResponseVo;
import com.geping.etl.utils.EnvUitl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.geping.etl.utils.sm3.SM3PrintUtil;

import static java.util.stream.Collectors.*;

@Slf4j
@RestController
public class Sys_UserController {

	@Resource
	private Syn1104UserService syn1104UserService;

	@Autowired
	private Sys_UserService sys_UserService;

	@Autowired
	private Sys_DepartmentService sys_DepartmentService;
	
	@Autowired
	private LogsService ls;
	
	@Autowired
	private Sys_UserAndOrgDepartmentService sys_UserAndOrgDepartmentService;

	@Autowired
	private Sys_OrgService sys_OrgService;

	@Autowired
	private Sys_SubjectService sys_subjectService;

	@Autowired
	private Report_InfoService reprotinfoservice;


	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static Pattern patternLoginId = Pattern.compile("^[\\u4e00-\\u9fa5_a-zA-Z0-9]{1,20}$");
	private static Pattern patternEName = Pattern.compile("^[a-zA-Z]{1,20}$");
	private static Pattern patternCName = Pattern.compile("^[\\u4e00-\\u9fa5]{1,20}$");

	//查询所有用户信息
	@RequestMapping(value="/sys_user",method=RequestMethod.GET)
	public ModelAndView getAllSys_user(){
		ModelAndView model = new ModelAndView();

		List<Sys_Org> list9 = sys_OrgService.findAllSysOrg();     //查询所有机构
		List<Sys_Org> orgList = new ArrayList<>();
		for (Sys_Org sys_org : list9){
			if (sys_org.getEnabled().equalsIgnoreCase("Y")){
				orgList.add(sys_org);
			}
		}
		List<Sys_Department> departmentList = sys_DepartmentService.findAllSys_Department();   //查询所有部门
		List<Sys_UserAndOrgDepartment> list = sys_UserAndOrgDepartmentService.findAllSysUser();   //查询所有用户(多表联查)

		list = list.stream().distinct().collect(toList());
		List<Sys_UserAndOrgDepartmentVo> voList = new ArrayList<>();
		List<Sys_DepartmentVo> departmentListVo = new ArrayList<>();

		if(Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))){
			list.forEach(user->{
				Sys_UserAndOrgDepartmentVo vo = new Sys_UserAndOrgDepartmentVo();
				BeanUtils.copyProperties(user, vo);
				departmentList.forEach(dept ->{
					if(dept.getDepartmentId().equals(user.getDepartid())){
						vo.setDepartmentname(dept.getDescription() + dept.getDepartmentName());
					}
				});
				voList.add(vo);
			});
			departmentList.forEach(dept -> {
				Sys_DepartmentVo vo = new Sys_DepartmentVo();
				BeanUtils.copyProperties(dept, vo);
				vo.setDepartmentName(vo.getDescription() + vo.getDepartmentName());
				departmentListVo.add(vo);
			});
		}else{
			list.forEach(user->{
				Sys_UserAndOrgDepartmentVo vo = new Sys_UserAndOrgDepartmentVo();
				BeanUtils.copyProperties(user, vo);
				voList.add(vo);
			});
			departmentList.forEach(dept -> {
				Sys_DepartmentVo vo = new Sys_DepartmentVo();
				BeanUtils.copyProperties(dept, vo);
				departmentListVo.add(vo);
			});
		}

		List<Sys_Subject> subjectList = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).collect(Collectors.toList());
//		Map<Integer, List<String>> orgidMap = orgList.stream().collect(groupingBy(Sys_Org::getOrgLayer,mapping(Sys_Org::getOrgId,toCollection(ArrayList::new))));
//		model.addObject("orgidMap", orgidMap);
		model.addObject("list", voList);
		model.addObject("subjectList", subjectList);
		model.addObject("orgList", orgList);
		model.addObject("departmentList",departmentListVo);
		model.setViewName("common/sys_user");
		return model;
	}


	//根据用户名模糊查询用户信息
	@RequestMapping(value="/getSys_user",method=RequestMethod.GET)
	public ModelAndView getSys_user(HttpServletRequest request){
		ModelAndView model = new ModelAndView();
		String userCname = "";
		try {
			userCname = URLDecoder.decode(request.getParameter("userCname").replaceAll("%","%25"), "utf-8");
			if (userCname.contains("%")){
				userCname = userCname.replace("%","djskdffhdfka");
			}else if (userCname.contains("_")){
				userCname = userCname.replace("_","djskdffhdfkb");
			}
			List<Sys_UserAndOrgDepartment> list = new ArrayList<>();
			if(StringUtils.isNotBlank(userCname)) {
				list = sys_UserAndOrgDepartmentService.findSysUserByName(userCname);
			}else {
				list = sys_UserAndOrgDepartmentService.findAllSysUser();
			}
			List<Sys_Org> orgList = sys_OrgService.findAllSysOrg();     //查询所有机构
			List<Sys_Department> departmentList = sys_DepartmentService.findAllSys_Department();   //查询所有部门
			if (userCname.contains("djskdffhdfka")){
				userCname = userCname.replace("djskdffhdfka","%");
			}else if (userCname.contains("djskdffhdfkb")){
				userCname = userCname.replace("djskdffhdfkb","_");
			}
			List<Sys_UserAndOrgDepartmentVo> voList = new ArrayList<>();
			List<Sys_DepartmentVo> departmentListVo = new ArrayList<>();
			if(Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))){
				list.forEach(user->{
					Sys_UserAndOrgDepartmentVo vo = new Sys_UserAndOrgDepartmentVo();
					BeanUtils.copyProperties(user, vo);
					departmentList.forEach(dept ->{
						if(dept.getDepartmentId().equals(user.getDepartid())){
							vo.setDepartmentname(dept.getDescription() + dept.getDepartmentName());
						}
					});
					voList.add(vo);
				});
				departmentList.forEach(dept -> {
					Sys_DepartmentVo vo = new Sys_DepartmentVo();
					BeanUtils.copyProperties(dept, vo);
					vo.setDepartmentName(vo.getDescription() + vo.getDepartmentName());
					departmentListVo.add(vo);
				});
			}else{
				list.forEach(user->{
					Sys_UserAndOrgDepartmentVo vo = new Sys_UserAndOrgDepartmentVo();
					BeanUtils.copyProperties(user, vo);
					voList.add(vo);
				});
				departmentList.forEach(dept -> {
					Sys_DepartmentVo vo = new Sys_DepartmentVo();
					BeanUtils.copyProperties(dept, vo);
					departmentListVo.add(vo);
				});
			}
			List<Sys_Subject> subjectList = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).collect(Collectors.toList());
			model.addObject("list",voList);
			model.addObject("orgList", orgList);
			model.addObject("subjectList", subjectList);
			model.addObject("departmentList",departmentListVo);
			model.addObject("userCname",userCname);
			model.setViewName("common/sys_user");
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return model;
	}


	//新增用户
	@ResponseBody
	@RequestMapping(value="/addSys_User",method=RequestMethod.POST)
	public ResponseVo addSys_User(HttpServletRequest request,HttpServletResponse response){
		String loginId_add = request.getParameter("loginId_add");
		String userEname_add = request.getParameter("userEname_add"); 
		String userCname_add = request.getParameter("userCname_add");
		String orgId_add = request.getParameter("orgId_add");
		String listStr = null;
		String listStr1 = null;
		boolean isOpenMoreOrg = request.getSession().getAttribute("user_more_org").equals("on") ? true : false;
		Map<String, String> sIdMapOrgId = new HashMap<>();
		if (isOpenMoreOrg) {
			List<String> subjectIdList = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).map(sys_subject -> sys_subject.getId().toString()).collect(toList());
			for (String subjectId : subjectIdList) {
				String key = "orgId_add"+subjectId;
				String value = request.getParameter(key);
				if (StringUtils.isNotBlank(value)) sIdMapOrgId.put(subjectId, value);
			}
			if (sIdMapOrgId.size() > 0) listStr = JSON.toJSONString(sIdMapOrgId);
		}

		String departId_add = request.getParameter("departId_add");

		ResponseVo responseVo = verifyAddUser(loginId_add, userEname_add, userCname_add, departId_add);
		if (responseVo.isResult() == false) return responseVo;

		boolean isOpenMoreDept = request.getSession().getAttribute("user_more_dept").equals("on") ? true : false;
		Map<String,String> sIdMapDeptId = new HashMap<>();
		if(isOpenMoreDept){
			List<String> subjectIdList1 = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).map(sys_subject -> sys_subject.getId().toString()).collect(toList());
			for(String subjectId : subjectIdList1){
				String key = "isDept_add" +subjectId;
				String value = request.getParameter(key);
				if (StringUtils.isNotBlank(value)) sIdMapDeptId.put(subjectId,value);
			}
			if (sIdMapDeptId.size() > 0 ) listStr1 = JSON.toJSONString(sIdMapDeptId);
		}

		String tel_add = request.getParameter("tel_add");
		String mobile_add = request.getParameter("mobile_add"); 
		String address_add = request.getParameter("address_add"); 
		String email_add = request.getParameter("email_add"); 
		String ip_add = request.getParameter("ip_add");
		String isDept_add = request.getParameter("isDept_add");
		Sys_User sysIsRepeat = sys_UserService.getOneByLoginId(loginId_add);
		List<String>erry=new ArrayList<>();

		try {
			if(sysIsRepeat != null){
				if(loginId_add.trim().equals(sysIsRepeat.getLoginId())){
					return new ResponseVo(false, "登录账号已存在");
				}
			}else{
				Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Sys_User sys = new Sys_User();
				sys.setLoginId(loginId_add);
				sys.setUserEname(userEname_add);
				sys.setUserCname(userCname_add);
				//sys.setPassword(SM3PrintUtil.getSM3Str("12345678"));
				sys.setPassword(sys_UserService.getInitPwd());
				if (!isOpenMoreOrg) sys.setOrgId(orgId_add);
				sys.setDepartId(departId_add);
				sys.setTel(tel_add);
				if (isOpenMoreOrg) sys.setEndDate(listStr);
				sys.setMobile(mobile_add);
				sys.setAddress(address_add);
				sys.setEmail(email_add);
				sys.setCreateTime(sdf.format(new Date()));
				sys.setLastModifyDate(sdf.format(new Date()));
				sys.setIp(ip_add);
				sys.setHandlename("");
				sys.setHandleperson(sys_User.getLoginid());
				sys.setHandledate(sdf.format(new Date()));
				if (!isOpenMoreDept)sys.setIsDept(isDept_add);
				else sys.setSystemDept(listStr1);
				sys.setFailNums("0");
				Sys_User user = sys_UserService.save(sys);
				//同步1104用户信息
//				if(Constants.ON.equals(EnvUitl.props.get("syn1104"))) {
//
//				}
				update1104(sys, 1, isOpenMoreOrg, sIdMapOrgId.get("30"), syn1104UserService, "", "");
				if(user != null){
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("新增用户"+loginId_add);
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode(sys_User.getOrgid());
					logs.setLogType("新增");
					ls.save(logs);   //添加日志信息
					return new ResponseVo(true, "新增成功！");
				}else{
					return new ResponseVo(false, "新增用户失败了");
				}
			}
		} catch (Exception e) {
			log.error("新增用户错误->{}",e);
			return new ResponseVo(false, "系统错误，请联系管理员");
		}
		return new ResponseVo(false, "系统错误，请联系管理员");
	}

	public ResponseVo verifyAddUser(String loginId, String eName, String cName, String deptId) {

		StringBuffer buffer = new StringBuffer();

		if (StringUtils.isBlank(deptId)) buffer.append("部门不可为空;");

		if (StringUtils.isBlank(loginId) || !patternLoginId.matcher(loginId).matches()) buffer.append("登录账号格式有误;");

		if (StringUtils.isBlank(eName) || !patternEName.matcher(eName).matches()) buffer.append("用户英文名格式有误;");

		if (StringUtils.isBlank(cName) || !patternCName.matcher(cName).matches()) buffer.append("用户中文名格式有误;");

		if (buffer.length() > 0) return new ResponseVo(false, buffer.toString());

		else return new ResponseVo(true, "");
	}

	//修改用户(不包括修改密码)
	@ResponseBody
	@RequestMapping(value="/editSys_User",method=RequestMethod.POST)
	public ResponseVo editSys_User(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("editId");
		String id_edit = request.getParameter("editId");
		String loginId_edit = request.getParameter("loginId_edit");
		List<String> subjectIdList = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).map(sys_subject -> sys_subject.getId().toString()).collect(toList());
		Map<String, String> sIdMapOrgId = new HashMap<>();
		for (String subjectId : subjectIdList) {
			String key = "orgId_edit"+subjectId;
			String value = request.getParameter(key);
			if (StringUtils.isNotBlank(value)) sIdMapOrgId.put(subjectId, value);
		}
		String listStr = null;
		if (sIdMapOrgId.size() > 0) listStr = JSON.toJSONString(sIdMapOrgId);
		String userEname_edit = request.getParameter("userEname_edit");
		String userCname_edit = request.getParameter("userCname_edit"); 
		String orgId_edit = request.getParameter("orgId_edit"); 
		String departId_edit = request.getParameter("departId_edit"); 
		String tel_edit = request.getParameter("tel_edit");
		String mobile_edit = request.getParameter("mobile_edit");
		String address_edit = request.getParameter("address_edit");
		String email_edit = request.getParameter("email_edit");
		String ip_edit = request.getParameter("ip_edit");
		String isEditLoginId = request.getParameter("isEditLoginId");


		String isDept_edit = request.getParameter("isDept_edit");
		List<String> subjectIdListDept = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).map(sys_subject -> sys_subject.getId().toString()).collect(toList());
		Map<String, String> sIdMapDeptId = new HashMap<>();
		for (String subjectId : subjectIdListDept) {
			String key = "isDept_edit"+subjectId;
			String value = request.getParameter(key);
			if (StringUtils.isNotBlank(value)) sIdMapDeptId.put(subjectId, value);
		}
		String listStrdept = null;
		if (sIdMapDeptId.size() > 0) listStrdept = JSON.toJSONString(sIdMapDeptId);
		boolean isOpenMoreOrg = false;
		boolean isOpenMoreDept = false;
		if ("on".equals(request.getSession().getAttribute("user_more_org"))) isOpenMoreOrg = true;
		if ("on".equals(request.getSession().getAttribute("user_more_dept"))) isOpenMoreDept = true;

		ResponseVo responseVo = verifyEditUser(id, orgId_edit, departId_edit, isDept_edit, listStr, listStrdept, isOpenMoreOrg, isOpenMoreDept);
		if (responseVo.isResult() == false) return responseVo;

		String oldLoginId = sys_UserService.findUserById(Integer.parseInt(id)).getLoginId();
		try {
			Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
			if(isEditLoginId.equals("1")){  //用户修改了登录账号
				Sys_User sysIsRepeat = sys_UserService.getOneByLoginId(loginId_edit);
				if(sysIsRepeat != null){  //如果返回对象不为空，即登录账号已存在 
					return new ResponseVo(false, "登录账号已存在");
				}else{   //如果返回对象为空，即登录账号不存在
					int result = 0 ;
					//若是开启多机构，则不对之前单机构修改
					if (isOpenMoreOrg) {

						if(isOpenMoreDept){
							result =sys_UserService.updateSysUserNoEditLoginIdDept(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit, listStr,listStrdept);

						}else {
							result = sys_UserService.updateSysUserNoEditLoginId(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit, listStr);
						}

					}else  {
						result = sys_UserService.updateSysUser(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,orgId_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit);
					}

					//同步1104用户信息
//					if(Constants.ON.equals(EnvUitl.props.get("syn1104"))) {
//						Sys_User sys = new Sys_User();
//						sys.setId(Integer.valueOf(id_edit));
//						sys.setLoginId(loginId_edit);
//						sys.setUserCname(userCname_edit);
//						sys.setUserEname(userEname_edit);
//						sys.setDepartId(departId_edit);
//						sys.setTel(tel_edit);
//						sys.setOrgId(orgId_edit);
//						syn1104UserService.syn1104UserInfo(sys);
//					}
					Sys_User sys = new Sys_User();
					sys.setId(Integer.valueOf(id_edit));
					sys.setLoginId(loginId_edit);
					sys.setUserCname(userCname_edit);
					sys.setUserEname(userEname_edit);
					sys.setDepartId(departId_edit);
					sys.setTel(tel_edit);
					sys.setOrgId(orgId_edit);
					update1104(sys, 2, isOpenMoreOrg, sIdMapOrgId.get("30"), syn1104UserService, oldLoginId, loginId_edit);
					if(result > 0){
						if (sys_User.getLoginid().equals(loginId_edit)){
							sys_User.setIsdept(isDept_edit);
							sys_User.setIp(ip_edit);
							sys_User.setOrgid(orgId_edit);
							sys_User.setId(Integer.parseInt(id_edit));
							sys_User.setId(Integer.parseInt(id_edit));
							sys_User.setUserename(userEname_edit);
							sys_User.setUsercname(userCname_edit);
							sys_User.setDepartid(departId_edit);
							sys_User.setTel(tel_edit);
							sys_User.setMobile(mobile_edit);
							sys_User.setAddress(address_edit);
							sys_User.setEmail(email_edit);
							request.getSession().removeAttribute("sys_User");
							request.getSession().setAttribute("sys_User",sys_User);
						}
						//添加日志信息
						Logs logs = new Logs();
						logs.setLoginId(sys_User.getLoginid());
						logs.setLogContent("修改用户"+loginId_edit);
						logs.setLogDate(sdf.format(new Date()));
						logs.setLogOrgCode(sys_User.getOrgid());
						logs.setLogType("修改用户");
						ls.save(logs);   //添加日志信息
						//开启多机构时,更新机构信息
						if (request.getSession().getAttribute("user_more_org").equals("on")) {
							Sys_UserAndOrgDepartment user = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
							user.setEnddate(listStr);
							request.getSession().removeAttribute("sys_User");
							request.getSession().setAttribute("sys_User",user);
						}
						if(request.getSession().getAttribute("user_more_dept").equals("on")){
							Sys_UserAndOrgDepartment user = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
							user.setSystemdept(listStrdept);
							request.getSession().removeAttribute("sys_User");
							request.getSession().setAttribute("sys_User",user);
						}
						return new ResponseVo(true, "修改成功!");
					}else{
						return new ResponseVo(false, "修改用户失败了");
					}
				}
			}else if(isEditLoginId.equals("0")){  //用户未修改登录账号
				//同步1104用户信息
//				if(Constants.ON.equals(EnvUitl.props.get("syn1104"))) {
//					Sys_User sys = new Sys_User();
//					sys.setId(Integer.valueOf(id_edit));
//					sys.setLoginId(loginId_edit);
//					sys.setUserCname(userCname_edit);
//					sys.setUserEname(userEname_edit);
//					sys.setDepartId(departId_edit);
//					sys.setTel(tel_edit);
//					sys.setOrgId(orgId_edit);
//					syn1104UserService.syn1104UserInfo(sys);
//				}
				Sys_User sys = new Sys_User();
				sys.setId(Integer.valueOf(id_edit));
				sys.setLoginId(loginId_edit);
				sys.setUserCname(userCname_edit);
				sys.setUserEname(userEname_edit);
				sys.setDepartId(departId_edit);
				sys.setTel(tel_edit);
				sys.setOrgId(orgId_edit);
				update1104(sys, 2, isOpenMoreOrg, sIdMapOrgId.get("30"), syn1104UserService, oldLoginId, loginId_edit);
				int result = 0 ;
				if (isOpenMoreOrg) {
					if(isOpenMoreDept){
						result =sys_UserService.updateSysUserNoEditLoginIdDept(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit, listStr,listStrdept);

					}else {
						result = sys_UserService.updateSysUserNoEditLoginId(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit, listStr);
					}
				} else  {
					result = sys_UserService.updateSysUser(Integer.valueOf(id_edit),loginId_edit,userEname_edit,userCname_edit,orgId_edit,departId_edit,tel_edit,mobile_edit,address_edit,email_edit,ip_edit,isDept_edit);
				}
				if(result > 0){
					if (sys_User.getLoginid().equals(loginId_edit)){
						sys_User.setIsdept(isDept_edit);
						sys_User.setIp(ip_edit);
						sys_User.setOrgid(orgId_edit);
						sys_User.setId(Integer.parseInt(id_edit));
						sys_User.setId(Integer.parseInt(id_edit));
						sys_User.setUserename(userEname_edit);
						sys_User.setUsercname(userCname_edit);
						sys_User.setDepartid(departId_edit);
						sys_User.setTel(tel_edit);
						sys_User.setMobile(mobile_edit);
						sys_User.setAddress(address_edit);
						sys_User.setEmail(email_edit);
						request.getSession().removeAttribute("sys_User");
						request.getSession().setAttribute("sys_User",sys_User);
					}
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("修改用户"+loginId_edit);
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode(sys_User.getOrgid());
					logs.setLogType("修改用户");
					ls.save(logs);   //添加日志信息

					//开启多机构时,更新机构信息
					if (request.getSession().getAttribute("user_more_org").equals("on")) {
						Sys_UserAndOrgDepartment user = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
						user.setEnddate(listStr);
						request.getSession().removeAttribute("sys_User");
						request.getSession().setAttribute("sys_User",user);
					}
					if(request.getSession().getAttribute("user_more_dept").equals("on")){
						Sys_UserAndOrgDepartment user = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
						user.setSystemdept(listStrdept);
						request.getSession().removeAttribute("sys_User");
						request.getSession().setAttribute("sys_User",user);
					}
					return new ResponseVo(true, "修改成功!");
				}else{
					return new ResponseVo(false, "修改用户失败了");
				}
			}else{
				return new ResponseVo(false, "修改用户失败了");
			}
		} catch (Exception e) {
			log.error("修改用户错误->{}",e);
			return new ResponseVo(false, "系统错误，请联系管理员");
		}
	}


	public ResponseVo verifyEditUser(String id, String orgId, String deptId, String isDept, String moreOrg, String moreDept, boolean isMoreOrg, boolean isMoreDept) {
		//获取所有组内人员信息
		Map<String, Map<String, List<String>>> mapInfo = new HashMap<>();
		Map<String, List<Report_Info>> gMap = reprotinfoservice.findAll().stream().filter(report_info -> StringUtils.isNotBlank(report_info.getUpdateTime())).collect(groupingBy(Report_Info::getSubjectId));
		if (gMap.containsKey("8")) {
			Map<String, List<Report_Info>> codeMap = gMap.get("8").stream().collect(groupingBy(Report_Info::getName));
			Set<Map.Entry<String, List<Report_Info>>> entries = codeMap.entrySet();
			for (Map.Entry<String, List<Report_Info>> entry : entries) {
				String key = entry.getKey();
				List<String> updateTimes = entry.getValue().stream().map(Report_Info::getUpdateTime).collect(Collectors.toList());
				for (String updateTime : updateTimes) {
					Map<String, Map<String, List<String>>> gInfo = JSON.parseObject(updateTime, Map.class);
					Set<Map.Entry<String, Map<String, List<String>>>> entries1 = gInfo.entrySet();
					for (Map.Entry<String, Map<String, List<String>>> stringMapEntry : entries1) {
						Map<String, List<String>> tMap = stringMapEntry.getValue();
						mapInfo.put(key, tMap);
					}
				}
			}
			gMap.remove("8");
		}
		Set<Map.Entry<String, List<Report_Info>>> entries = gMap.entrySet();
		for (Map.Entry<String, List<Report_Info>> entry : entries) {
			Map<String, List<Report_Info>> tMap = entry.getValue().stream().collect(groupingBy(Report_Info::getName));
			Set<Map.Entry<String, List<Report_Info>>> entries1 = tMap.entrySet();
			for (Map.Entry<String, List<Report_Info>> stringListEntry : entries1) {
				String key = stringListEntry.getKey();
				List<String> updateTimes = stringListEntry.getValue().stream().map(Report_Info::getUpdateTime).collect(Collectors.toList());
				for (String updateTime : updateTimes) {
					Map<String, List<String>> gInfo = JSON.parseObject(updateTime, Map.class);
					mapInfo.put(key, gInfo);
				}
			}
		}

		ResponseVo responseVo = new ResponseVo(true,"");
		Sys_User user = sys_UserService.findUserById(Integer.valueOf(id));
		boolean isInGroup = false;
		StringBuffer buffer = new StringBuffer("该人员在");
		Set<Map.Entry<String, Map<String, List<String>>>> entries1 = mapInfo.entrySet();
		for (Map.Entry<String, Map<String, List<String>>> stringMapEntry : entries1) {
			String codeName = stringMapEntry.getKey();
			Map<String, List<String>> tempMap = stringMapEntry.getValue();
			Set<Map.Entry<String, List<String>>> entries2 = tempMap.entrySet();
			List<String> groupNameList = new ArrayList<>();
			for (Map.Entry<String, List<String>> stringListEntry : entries2) {
				String groupName = stringListEntry.getKey();
				if (stringListEntry.getValue().contains(user.getLoginId())) {
					isInGroup = true;
					groupNameList.add(groupName);
				}
			}
			if (groupNameList.size() > 0) {
				buffer.append(codeName);
				buffer.append("中");
				buffer.append(groupNameList);
				groupNameList.clear();
			}
		}
		buffer.append("存在,");

		if (!user.getDepartId().equals(deptId)) {
			buffer.append("不可修改部门,");
			responseVo.setResult(false);
		}
		boolean one1 = true;
		if (isMoreOrg) {
			if (StringUtils.isBlank(user.getEndDate())) {
				buffer.append("不可修改机构,");
				responseVo.setResult(false);
			} else {
				Map<String, String> oldMap = JSON.parseObject(user.getEndDate(), Map.class);
				Map<String, String> newMap = JSON.parseObject(moreOrg, Map.class);
				Set<Map.Entry<String, String>> set = newMap.entrySet();
				for (Map.Entry<String, String> entry : set) {
					String key = entry.getKey();
					String value = entry.getValue();
					if (oldMap.get(key) == null || !oldMap.get(key).equals(value) ) {
						buffer.append("不可修改机构,");
						one1 =false;
						responseVo.setResult(false);
						break;
					} else {
						oldMap.remove(key);
					}
				}
				if (oldMap.size() > 0 && one1) {
					buffer.append("不可修改机构,");
					responseVo.setResult(false);
				}
				//将判断不可修改机构逻辑移入到开关里面
				if (!user.getOrgId().equals(orgId)) {
					buffer.append("不可修改机构,");
					responseVo.setResult(false);
				}
			}
		}
		boolean one = true;
		if (isMoreDept) {
			if (StringUtils.isBlank(user.getSystemDept())) {
				buffer.append("不可修改是否分部门,");
				responseVo.setResult(false);
			} else {
				Map<String, String> oldMap = JSON.parseObject(user.getSystemDept(), Map.class);
				Map<String, String> newMap = JSON.parseObject(moreDept, Map.class);
				Set<Map.Entry<String, String>> set = newMap.entrySet();
				for (Map.Entry<String, String> entry : set) {
					String key = entry.getKey();
					String value = entry.getValue();
					if (oldMap.get(key) == null || !oldMap.get(key).equals(value)) {
						buffer.append("不可修改是否分部门,");
						one = false;
						responseVo.setResult(false);
						break;
					} else {
						oldMap.remove(key);
					}
				}
				if (oldMap.size() > 0 && one) {
						buffer.append("不可修改是否分部门,");
						responseVo.setResult(false);
				}
				//将判断不可修改分部门逻辑移入到开关里面
				if (!user.getIsDept().equals(isDept)) {
					buffer.append("不可修改是否分部门,");
					responseVo.setResult(false);
				}
			}
		}
		String result = buffer.toString();
		if (result.endsWith(",")) result = result.substring(0, result.length()-1);
		responseVo.setMessage(result);
		if (isInGroup == false) responseVo.setResult(true);
		return responseVo;
	}

	/**
	 * 1104用户同步方法
	 * @param sys_user            需要同步的用户信息
	 * @param operateNum		  同步类型
	 * @param isOpenMoreOrg       是否开启多机构开关
	 * @param newOrgId			  修改后新的orgId
	 * @param syn1104UserService
	 * @param oldLoginId          数据库查询的原logId
	 * @param loginId             修改后的loginId
	 */
	public void update1104(Sys_User sys_user, int operateNum, boolean isOpenMoreOrg, String newOrgId, Syn1104UserService syn1104UserService, String oldLoginId, String loginId) {
		if(Constants.ON.equals(EnvUitl.props.get("syn1104"))) {
			switch (operateNum) {
				case Constants.DELETE_OPERATE:
					syn1104UserService.syn1104DeleteUser(loginId);
					break;
				case Constants.ADD_OPERATE:
					if (isOpenMoreOrg) {
						if (StringUtils.isNotBlank(newOrgId)) {
							sys_user.setOrgId(newOrgId);
							syn1104UserService.syn1104UserInfo(sys_user);
						}
					}else {
						syn1104UserService.syn1104UserInfo(sys_user);
					}
					break;
				case Constants.EDIT_OPERATE:
					if (isOpenMoreOrg) {
						if (StringUtils.isNotBlank(newOrgId)) {
							sys_user.setOrgId(newOrgId);
							syn1104UserService.syn1104UserInfo(sys_user);
						} else {
							//删除，按照数据库中原loginId删除，不需要判断loginId是否修改了
							syn1104UserService.syn1104DeleteUser(oldLoginId);
						}
					} else {
						syn1104UserService.syn1104UserInfo(sys_user);
					}
					break;
				default:
					break;
			}
		}
	}

	
	
	//申请修改
	@RequestMapping(value="/applyEdit",method=RequestMethod.POST)
	public void applyEdit(HttpServletRequest request,HttpServletResponse response){
			PrintWriter out;
			try {
				request.setCharacterEncoding("utf-8");
				out = response.getWriter();
				String id = request.getParameter("id");
				String desc = request.getParameter("desc");
				Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				int result = sys_UserService.applyEdit(Integer.valueOf(id), desc,"申请修改",sys_User.getLoginid(),sdf.format(new Date()));
				if(result > 0) {
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("申请修改用户,"+desc);
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode(sys_User.getOrgid());
					logs.setLogType("申请修改用户");
					ls.save(logs);   //添加日志信息
					out.write("1");
				}else {
					out.write("0");
				}
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	}
	
	
	//申请重置密码
	@RequestMapping(value="/applyReaptPwd",method=RequestMethod.GET)
	public void applyReaptPwd(HttpServletRequest request,HttpServletResponse response){
			PrintWriter out;
			try {
				request.setCharacterEncoding("utf-8");
				out = response.getWriter();
				String id = request.getParameter("id");
				//String pwd = SM3PrintUtil.getSM3Str(request.getParameter("pwd"));
				String pwd=sys_UserService.getInitPwd();
				Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				int result = sys_UserService.applyReaptPwd(Integer.valueOf(id), pwd,"申请重置密码",sys_User.getLoginid(),sdf.format(new Date()));
				if(result > 0) {
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("申请重置密码");
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode(sys_User.getOrgid());
					logs.setLogType("申请重置密码");
					ls.save(logs);   //添加日志信息
					out.write("1");
				}else {
					out.write("0");
				}
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	}
	
	
	//修改用户密码
	@RequestMapping(value="/editPasswordSys_User",method=RequestMethod.GET)
	public void editPasswordSys_User(HttpServletRequest request,HttpServletResponse response){
		PrintWriter out = null;
		boolean isCheck = true;
		if (null != EnvUitl.props.getProperty("isRepeat") && "off".equals(EnvUitl.props.getProperty("isRepeat"))) {
			isCheck = false;
		}
		try {
			//后端做密码策略的验证
			response.setContentType("text/html;charset=utf-8");
			out = response.getWriter();
			PwdPolicyService pwdPolicyService=PwdPolicyServiceDispatcher.getPwdPolicyService(EnvUitl.props.getProperty(Constants.PWD_POLICY_CUSTOMER));
			if(!pwdPolicyService.validate(request.getParameter("password_edit"))){
				out.write(pwdPolicyService.getPwdPolicy().getTip());
				return;
			}
			Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
			Integer editPasswordId = sys_User.getId();
			Sys_User user = sys_UserService.findUserById(sys_User.getId());
			String str = null;
			boolean isrepeat = false;
			String password_edit = SM3PrintUtil.getSM3Str(request.getParameter("password_edit"));
			if(user != null) {
				 str = user.getPwdstr();
				 if(str == null || str.equals("")) {
					 str = password_edit;
				 }else {
					 String [] pwdArray = str.split(",");
					 if (isCheck) {
						 for(int i = 0;i<pwdArray.length;i++) {
							 if(password_edit.equals(pwdArray[i])) {
								 isrepeat = true;
								 break;
							 }
						 }
					 }
					 str = str + "," + password_edit;
				 }
			}
			int result = 0;
			String isFirstLogin = sys_User.getIsfirstlogin();
			if(isrepeat) {
				out.write("2");
			}else {
				result = sys_UserService.editPasswordSys_User(Integer.valueOf(editPasswordId),password_edit,sdf.format(new Date()),str);
				if(isFirstLogin.equals("Y")){  //首次登录
					sys_UserService.updateSomeSysUser(sdf.format(new Date()),"N",Integer.valueOf(editPasswordId));
				}
				if(result > 0){
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("修改密码");
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode(sys_User.getOrgid());
					logs.setLogType("修改密码");
					ls.save(logs);   //添加日志信息
					out.write("1");
				}else{
					out.write("0");
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null) {
				out.flush();
				out.close();
			}
		}
	}

	
	//申请解锁用户
	@RequestMapping(value="/applyNoLock",method=RequestMethod.POST)
	public void applyNoLock(HttpServletRequest request,HttpServletResponse response){
			PrintWriter out;
			try {
				request.setCharacterEncoding("utf-8");
				out = response.getWriter();
				String id = request.getParameter("id");
				Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				int result = sys_UserService.applyNoLock(Integer.valueOf(id),"申请解锁",sys_User.getLoginid(),sdf.format(new Date()));
				if(result > 0) {
					//添加日志信息
					Logs logs = new Logs();
					logs.setLoginId(sys_User.getLoginid());
					logs.setLogContent("申请解锁用户");
					logs.setLogDate(sdf.format(new Date()));
					logs.setLogOrgCode("");
					logs.setLogType("申请解锁用户");
					ls.save(logs);   //添加日志信息
					out.write("1");
				}else {
					out.write("0");
				}
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	}
	
	
	//申请锁定用户
	@RequestMapping(value="/applyDoLock",method=RequestMethod.POST)
	public void applyDoLock(HttpServletRequest request,HttpServletResponse response){
				PrintWriter out;
				try {
					request.setCharacterEncoding("utf-8");
					out = response.getWriter();
					String id = request.getParameter("id");
					String reason = request.getParameter("reason");
					Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					int result = sys_UserService.applyDoLock(Integer.valueOf(id),"申请锁定",sys_User.getLoginid(),sdf.format(new Date()),reason);
					if(result > 0) {
						//添加日志信息
						Logs logs = new Logs();
						logs.setLoginId(sys_User.getLoginid());
						logs.setLogContent("申请锁定用户");
						logs.setLogDate(sdf.format(new Date()));
						logs.setLogOrgCode("");
						logs.setLogType("申请锁定用户");
						ls.save(logs);   //添加日志信息
						out.write("1");
					}else {
						out.write("0");
					}
					out.flush();
					out.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
	}
	

	//修改用户是否锁定
	@RequestMapping(value="/editIsLockedSys_User",method=RequestMethod.POST)
	public void editIsLockedSys_User(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		String isLocked = request.getParameter("isLocked");
		int result = 0;
		JSONObject permision = new JSONObject();
		PrintWriter out;
		try {
			request.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			if(isLocked.equals("Y")){
				String reason = request.getParameter("reason");
				result = sys_UserService.lockedUser(Integer.valueOf(id), isLocked, reason);
				permision.put("result",result);
				out.print(permision.toString());
			}else if(isLocked.equals("N")){
				result = sys_UserService.editIsLockedSys_User(Integer.valueOf(id), isLocked);
				permision.put("result",result);
				out.print(permision.toString());
			}else{
				permision.put("result",result);
				out.print(permision.toString());
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	//逻辑删除用户
	@RequestMapping(value="/deleteSys_User",method=RequestMethod.POST)
	public void deleteSys_User(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		String loginId = request.getParameter("loginId");
		int result = 0;
		if(Constants.ON.equals(EnvUitl.props.get("syn1104"))) {
			syn1104UserService.syn1104DeleteUser(loginId);
		}
		result = sys_UserService.deleteSys_User(Integer.valueOf(id));
		JSONObject permision = new JSONObject();
		PrintWriter out;
		try {
			out = response.getWriter();
			permision.put("result",result);
			out.print(permision.toString());
			out.flush();
			out.close();
		} catch (IOException e){
			e.printStackTrace();
		}
	}

	
	
	//同意申请
	@RequestMapping(value="/agreenApply",method=RequestMethod.POST)
	public void agreenApply(HttpServletRequest request,HttpServletResponse response){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			request.setCharacterEncoding("utf-8");
			String id = request.getParameter("id");
			String applyname = request.getParameter("applyname");
			int result = 0;
			if(applyname.equals("申请新增")){
				result = sys_UserService.agreenAddOrEdit(Integer.valueOf(id)," ");
			}else if(applyname.equals("申请修改")){
				result = sys_UserService.agreenAddOrEdit(Integer.valueOf(id),"同意修改");
			}else if(applyname.equals("申请重置密码")){
				result = sys_UserService.agreenReapt(Integer.valueOf(id));
				//同意重置密码,将是否首次登录设置为Y
                sys_UserService.updateFirstLoginStatus(Integer.valueOf(id),"Y");
			}else if(applyname.equals("申请锁定")){
				result = sys_UserService.agreenLock(Integer.valueOf(id),"Y");
			}else if(applyname.equals("申请解锁")){
				result = sys_UserService.agreenNoLock(Integer.valueOf(id),"N");
				//将锁定次数清零
				sys_UserService.updateTimeById("0",Integer.valueOf(id));
			}else{
				
			}
			if(result > 0) {
				out.write("1");
			}else {
				out.write("0");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(out != null) {
				out.flush();
				out.close();
			}
		}
	}
	
	
	//拒绝申请
	@RequestMapping(value="/refuseApply",method=RequestMethod.POST)
	public void refuseApply(HttpServletRequest request,HttpServletResponse response){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			request.setCharacterEncoding("utf-8");
			String id = request.getParameter("id");
			String applyname = request.getParameter("applyname");
			int result = 0;
			if(applyname.equals("申请新增")){
				result = sys_UserService.refuseAddOrEdit(Integer.valueOf(id));
			}else if(applyname.equals("申请修改")){
				result = sys_UserService.refuseAddOrEdit(Integer.valueOf(id));
			}else if(applyname.equals("申请重置密码")){
				result = sys_UserService.refuseSomeHandle(Integer.valueOf(id));
			}else if(applyname.equals("申请锁定")){
				result = sys_UserService.refuseSomeHandle(Integer.valueOf(id));
			}else if(applyname.equals("申请解锁")){
				result = sys_UserService.refuseSomeHandle(Integer.valueOf(id));
			}else{
				
			}
			if(result > 0) {
				out.write("1");
			}else {
				out.write("0");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(out != null) {
				out.flush();
				out.close();
			}
		}
	}
	
	
	//Excel导出用户信息
	/*@RequestMapping(value="/exportExcelSys_User",method=RequestMethod.GET)
	public void exportExcelSys_User(HttpServletRequest request,HttpServletResponse response){
		//headers:excel中表列标题名
		String[] headers ={"ID","登录账号","用户英文名","用户中文名","密码","机构编号","机构名称","部门ID","部门名称","联系电话","移动电话","地址","邮箱","是否锁定用户","锁定原因","开始时间","结束时间","创建时间","描述","启用标识","是否删除","最后登录时间","最后修改密码日期","是否为首次登录"};  
		List<Sys_UserAndOrgDepartment> list = sys_UserAndOrgDepartmentService.findAllSysUser();   //查询所有用户(多表联查)
		ExcelExportUtils<Sys_UserAndOrgDepartment> eeu = new ExcelExportUtils<Sys_UserAndOrgDepartment>();
		String fileName = "人员信息记录.xls";   //设置下载的文件名称
		String title = "人员信息记录";          //Excel表格sheet名称
		eeu.exportExcel(request,response,fileName,title,headers,list);
	}*/

	//Excel导入用户信息
	@RequestMapping(value="/importExcelSys_User",method=RequestMethod.POST)
	public String importExcelSys_User(HttpServletRequest request,HttpServletResponse response,@RequestParam("fileToUpload") MultipartFile file) throws IOException{
		//判断文件是否是以规定的格式结尾的（excel格式）
		if(file.getSize()>1048576){
			return "上传的文件大小不能超过2MB,请重新上传！";
		
		}
		if(!file.getOriginalFilename().endsWith(".xls")){
			
			return "请上传正确的文件格式！";
		}else {
			InputStream inputStream=file.getInputStream();
			//记录总的成功数
			int successNum=0;
			int linknum=0;
			//记录用户的操作信息
			String recording="";
			//格式化文件为正确的文件格式
					HSSFWorkbook workbook=null; 
					try {
						//创建一个工作薄
						workbook=new HSSFWorkbook(inputStream);
						//创建一张工作表
						HSSFSheet sheet=workbook.getSheetAt(0);
						//获取到文件的最后一行
						int lastRowNum=sheet.getLastRowNum();
						String[] firstCellName={"ID","登录账号","用户英文名","用户中文名","密码","机构编号","机构名称","部门ID","部门名称","联系电话","移动电话","地址","邮箱","是否锁定用户","锁定原因","开始时间","结束时间","创建时间","描述","启用标识","是否删除","最后登录时间","最后修改密码日期","是否为首次登录"};
						//判断用户是否上传的是一个空文件
						if(lastRowNum==0){
							return recording="文件导入模板有误，请在页面点击导出下载正确的模板!";
						}
						for (int i = 0; i<=lastRowNum; i++) {
							//判断是否为空行
							HSSFRow hssfrow=sheet.getRow(i);
							if(hssfrow==null)
							{
								continue;
							}
							HSSFRow row =sheet.getRow(i);
							//判断文件是否是合格的模板在进行导入
							if (i==0) {
								if(row.getLastCellNum()==firstCellName.length){
									for (int j = 0; j <row.getLastCellNum(); j++) {
										if(!firstCellName[j].equals(row.getCell(j)+"")){
											return recording="文件导入模板有误，请在页面点击导出下载正确的模板!";
										}
									}
									continue;
								}else {
									
									return recording="文件导入模板有误，请在页面点击导出下载正确的模板!";
								}
							}
							
							String user3=sys_UserService.findLoginIdSys_User(String.valueOf(row.getCell(1)));
							//判读用户是否已经存在数据库之中，如果没有则执行下一步操作，不予许用户名相同的用户出现
							if(user3==null){
								//将excel表中的数据写入到对象中
								Sys_User user=new Sys_User();
								HSSFCell cell=row.getCell(1);
								//使用正则表达式对用户输入的信息进行校验

								//判断用户名
								String regex = "^([a-zA-Z][0-9]){1,10}$|^([\\u4e00-\\u9fa5]){1,10}$"; 
								Matcher m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(1)).trim()); 
								if(m.find() ){
									cell=row.getCell(1);
									user.setLoginId(String.valueOf(cell));
								}else {
									
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因用户名为数字英文组合或中文!"+"</br>";
									continue;
								}

								//判断用户英文名
								regex ="^[a-zA-Z]{1,10}"; 
								m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(2)).trim());
								if(m.find()){
									cell=row.getCell(2);
									user.setUserEname(String.valueOf(cell));
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因英文名不能为空，长度不能超过10位!"+"</br>";
									continue;
								}


								//判断用户中文名
								regex ="^[\\u4e00-\\u9fa5]{1,10}$"; 
								m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(3)).trim());
								if(m.find()){
									cell=row.getCell(3);
									user.setUserCname(String.valueOf(cell));
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因中文名不能为空,长度不能超过10位!"+"</br>";
									continue;
								}


								//判断用户密码
								regex = "^[a-zA-Z]\\w{5,10}"; 
								m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(4)).trim());
								if(m.find()){
									cell=row.getCell(4);
									user.setPassword(String.valueOf(cell));
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因密码不能为空，长度在5到10位之间!"+"</br>";
									continue;
								}

								//判断机构编号
								regex = "[0-9]{0,10}"; 
								m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(5)).trim());
								if(m.find()){
									cell=row.getCell(5);
									user.setOrgId(String.valueOf(cell));
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因机构编号必须由数字组成，且长度不超过10位!"+"</br>";
									continue;
								}

								//判断部门编号
								regex = "[0-9]{0,10}"; 
								m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(7)).trim());
								if(m.find()){
									cell=row.getCell(7);
									user.setDepartId(String.valueOf(cell));
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因部门编号必须由数字组成，且长度不超过10位!"+"</br>";
									continue;
								}

								//判断联系电话
								if((!String.valueOf(row.getCell(9)).trim().isEmpty())){
									user.setTel("");
								}else{
									regex = "^((13\\d{9}$)|(15[0,1,2,3,5,6,7,8,9]\\d{8}$)|(18[0,2,5,6,7,8,9]\\d{8}$)|(147\\d{8})$)"; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(9)).trim());
									if(m.find()){

										cell=row.getCell(9);
										user.setTel(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因电话号码格式有误!"+"</br>";
										continue;
									}
								}

								//判断移动电话
								if((!String.valueOf(row.getCell(10)).trim().isEmpty())){
									user.setMobile("");
								}else{
									regex = "^((13\\d{9}$)|(15[0,1,2,3,5,6,7,8,9]\\d{8}$)|(18[0,2,5,6,7,8,9]\\d{8}$)|(147\\d{8})$)"; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(10)).trim());
									if(m.find()){

										cell=row.getCell(10);
										user.setMobile(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因移动电话号码格式有误!"+"</br>";
										continue;
									}
								}

								//判断地址
								if((!String.valueOf(row.getCell(11)).trim().isEmpty())){
									user.setAddress(null);
								}else{
									cell=row.getCell(11);
									user.setAddress(String.valueOf(cell));
									
								}
								
								//判断邮箱
								if((!String.valueOf(row.getCell(12)).trim().isEmpty())){
									user.setEmail(null);
								}else{
									regex = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+"; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(12)).trim());
									if(m.find()){
										cell=row.getCell(12);
										user.setEmail(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因邮箱格式有误!"+"</br>";
										continue;
									}
								}

								//判断是否锁定
								if((!String.valueOf(row.getCell(13)).trim().isEmpty())){
									user.setIsLocked("N");
								}else{
									regex = "^Y$|^N$"; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(13)).trim());
									if(m.find()){
										cell=row.getCell(13);
										user.setIsLocked(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因只能选择Y或N!"+"</br>";
										continue;
									}
								}
								
								//判断锁定原因
								if((!String.valueOf(row.getCell(14)).trim().isEmpty())){
									user.setUserLockedReson(null);
								}else{
									regex = "^([a-zA-z][\\u4e00-\\u9fa5]){0,25}"; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(14)).trim());
									if(m.find()){
										cell=row.getCell(14);
										user.setUserLockedReson(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因长度超出范围!"+"</br>";
										continue;
									}
								}
								
								
								//判断开始时间
								if((!String.valueOf(row.getCell(15)).trim().isEmpty())){
									user.setStartDate(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(15)).trim());
									if(m.find()){
										cell=row.getCell(15);
										user.setStartDate(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因开始时间格式有误!"+"</br>";
										continue;
									}
								}
								
								//判读结束时间
								if((!String.valueOf(row.getCell(16)).trim().isEmpty())){
									user.setEndDate(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(16)).trim());
									if(m.find()){
										cell=row.getCell(16);
										user.setEndDate(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因结束时间格式有误!"+"</br>";
										continue;
									}
								}
								
								//判断创建时间
								if((!String.valueOf(row.getCell(17)).trim().isEmpty())){
									user.setCreateTime(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(17)).trim());
									if(m.find()){
										cell=row.getCell(17);
										user.setCreateTime(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因创建时间格式有误!"+"</br>";
										continue;
									}
								}
								
								//判断描述
								if((!String.valueOf(row.getCell(18)).trim().isEmpty())){
									user.setDescription(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(18)).trim());
									if(m.find()){
										cell=row.getCell(18);
										user.setDescription(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因添加描述失败!"+"</br>";
										continue;
									}
								}
								
								
								//判断启用标识
								if((!String.valueOf(row.getCell(19)).trim().isEmpty())){
									user.setEnabled(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(19)).trim());
									if(m.find()){
										cell=row.getCell(19);
										user.setEnabled(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因启用标识有误!"+"</br>";
										continue;
									}
								}
								
								//判断是否删除
								if((!String.valueOf(row.getCell(20)).trim().isEmpty())){
									user.setIsDelete("N");
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(20)).trim());
									if(m.find()){
										cell=row.getCell(20);
										user.setIsDelete(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因添加是否删除时失败!"+"</br>";
										continue;
									}
								}
							
								
								//判读最后登录时间
								if((!String.valueOf(row.getCell(21)).trim().isEmpty())){
									user.setLastLoginDate(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(21)).trim());
									if(m.find()){
										cell=row.getCell(21);
										user.setLastLoginDate(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"添加用户名为“"+String.valueOf(cell)+"”时失败原因最后登录时间格式有误!"+"</br>";
										continue;
									}
								}
								
								//判断最后修改密码日期
								if((!String.valueOf(row.getCell(22)).trim().isEmpty())){
									user.setLastModifyDate(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(22)).trim());
									if(m.find()){
										cell=row.getCell(22);
										user.setLastModifyDate(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败原因最后修改密码日期格式有误!"+"</br>";
										continue;
									}
								}
								
								//判断是否首次登录
								if((!String.valueOf(row.getCell(23)).trim().isEmpty())){
									user.setIsFirstLogin(null);
								}else{
									regex = ""; 
									m = Pattern.compile(regex).matcher(String.valueOf(row.getCell(23)).trim());
									if(m.find()){
										cell=row.getCell(23);
										user.setIsFirstLogin(String.valueOf(cell));
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败请检查首次登录字段!"+"</br>";
										continue;
									}
								}
								
								
								
									//如果上述条件都满足，那么进行数据的添加
									if(sys_UserService.save(user)!=null){
										successNum++;
									}else {
										linknum++;
										recording+=linknum+"、添加用户名为“"+String.valueOf(cell)+"”时失败遇到未知错误!";
									}
							}else{
								if(String.valueOf(user3).isEmpty()){
									
									recording+="添加第："+row+"条数据时失败用户名不能为空!"+"</br>";
								}else {
									linknum++;
									recording+=linknum+"、添加用户名为“"+String.valueOf(user3)+"”时失败用户已经存在!"+"</br>";
								}
							}
							
						}
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}finally{
						//关闭流
						try {
							workbook.close();
							inputStream.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
			//日志操作
			 Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
			 Logs logs = new Logs();
			 logs.setLoginId(sys_User.getLoginid());
			 logs.setLogContent("进行excel导入用户操作");
			 logs.setLogDate(sdf.format(new Date()));
			 logs.setLogOrgCode(sys_User.getOrgid());
			 logs.setLogType("进行用户导入操作");
			 ls.save(logs);   //添加日志信息
			return recording+"成功"+successNum+"条";
		}

	}


	//后门程序手动触发同步个人银行信息
	@RequestMapping(value = "/synPersonBankInfo", method = RequestMethod.GET)
	public String synPersonBankInfo(){
		try {
			log.info("synPersonBankInfo start");
			if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
				//查询所有部门员工信息并分组，并将分组好的信息同步到个人银行项目供ftp使用
				sys_UserAndOrgDepartmentService.synUserInfoToPersonBank();
			} else {
				log.info("synPersonBankInfo taiwan.user config is not open");
			}
			log.info("synPersonBankInfo end");
			return "Success";
		}catch (Exception e){
			log.error("synPersonBankInfo exception, e = {}", e);
			return "Fail";
		}
	}

}
